package com.mydesign.demo.service.Impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.mydesign.demo.bean.*;
import com.mydesign.demo.mapper.*;
import com.mydesign.demo.model.ReturnResult;
import com.mydesign.demo.service.StoreToAssignmentService;
import com.mydesign.demo.util.DistanceUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class StoreToAssignmentServiceImpl implements StoreToAssignmentService {
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private StoreToAssignmentMapper storeToAssignmentMapper;
    @Autowired
    private WxuserMapper wxuserMapper;
    @Autowired
    private StoreCommentMapper storeCommentMapper;
    @Autowired
    private StoreUserFollowMapper storeUserFollowMapper;
    @Override
    public ReturnResult selectMyReceiving(HttpServletRequest request) {
        String storeId = request.getParameter("storeId");
        if(StringUtils.isEmpty(storeId)) return new ReturnResult("-1","无小店");
        StoreToAssignmentExample assignmentExample=new StoreToAssignmentExample();
        assignmentExample.createCriteria().andStoreIdEqualTo(storeId);
        List<StoreToAssignment> storeToAssignments = storeToAssignmentMapper.selectByExample(assignmentExample);
        List<Map<String, Object>> mapList=new ArrayList<>();
        for(StoreToAssignment e:storeToAssignments){
            Map<String, Object> map = BeanUtil.beanToMap(e);
            String userId = e.getUserId();
            WxuserExample wxuserExample=new WxuserExample();
            wxuserExample.createCriteria().andUserIdEqualTo(userId);
            List<Wxuser> wxusers = wxuserMapper.selectByExample(wxuserExample);
            String format = DateUtil.format(e.getCreateTime(), "yyyy-MM-dd");
            map.put("createTime",format);
            Wxuser wxuser = wxusers.get(0);
            map.put("userName",wxuser.getUserName());
            mapList.add(map);
        }
        return ReturnResult.dataSuccess(mapList);
    }

    @Override
    public ReturnResult selectMyOrder(HttpServletRequest request) {
        String userId = request.getParameter("userId");
        if(StringUtils.isEmpty(userId)) return new ReturnResult("-1","未登录");
        StoreToAssignmentExample assignmentExample=new StoreToAssignmentExample();
        assignmentExample.createCriteria().andUserIdEqualTo(userId);
        List<StoreToAssignment> storeToAssignments = storeToAssignmentMapper.selectByExample(assignmentExample);
        List<Map<String, Object>> mapList=new ArrayList<>();
        for (StoreToAssignment e:storeToAssignments){
            Map<String, Object> map = BeanUtil.beanToMap(e);
            String storeId = e.getStoreId();
            if(StringUtils.isNotEmpty(storeId)){
                Store store = storeMapper.selectByPrimaryKey(storeId);
                String format = DateUtil.format(e.getCreateTime(), "yyyy-MM-dd");
                map.put("createTime",format);
                map.put("storeName",store.getShopName());
            }else {
                map.put("storeName","未被接单");
            }
            mapList.add(map);
        }
        return ReturnResult.dataSuccess(mapList);
    }

    @Override
    public ReturnResult selectCancelOrder(HttpServletRequest request) {
        StoreToAssignmentExample storeToAssignmentExample=new StoreToAssignmentExample();
        storeToAssignmentExample.createCriteria().andStatusEqualTo(6);
        List<StoreToAssignment> storeToAssignments = storeToAssignmentMapper.selectByExample(storeToAssignmentExample);
        List<Map<String, Object>> mapList=new ArrayList<>();
        for (StoreToAssignment e:storeToAssignments){
            Map<String, Object> map = BeanUtil.beanToMap(e);
            String shootingAddress = e.getShootingAddress();
            String[] split = shootingAddress.split(",");
            map.put("shootingAddress",split[1]);
            map.put("shootingTimeStart",DateUtil.format(e.getShootingTimeStart(), "yyyy-MM-dd"));
            String details = e.getDetails();
            char[] chars = details.toCharArray();
            String s="";
            if(chars.length>5){
                for(int i=0;i<4;i++){
                    s=s+chars[i];
                }
                map.put("details",s+"...");
            }else {
                map.put("details",e.getDetails());
            }
            mapList.add(map);
        }
        return ReturnResult.dataSuccess(mapList);
    }

    @Override
    public ReturnResult selectOrderDetails(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        if(storeToAssignment==null) return new ReturnResult("-1","未找到订单");
        Map<String, Object> map = BeanUtil.beanToMap(storeToAssignment);
        String shootingAddress = storeToAssignment.getShootingAddress();
        String[] split = shootingAddress.split(",");
        map.put("shootingAddress",split[0]+split[1]);
        String s = split[1];
        char[] chars = s.toCharArray();
        String lo = "";
        if(chars.length>15){
            for(int i=0;i<8;i++){
                lo=lo+chars[i];
            }
            lo=lo+"...";
            map.put("addresss",lo);
        }else {
            map.put("addresss",split[1]);
        }
        map.put("latitude",split[2]);
        map.put("longitude",split[3]);
        if(StringUtils.isNotEmpty(storeToAssignment.getStoreId())){
            String storeId = storeToAssignment.getStoreId();
            Store store = storeMapper.selectByPrimaryKey(storeId);
            map.put("storeShop",store.getImgShop());
            map.put("shoreName",store.getShopName());
            String userId = store.getUserId();
            WxuserExample wxuserExample=new WxuserExample();
            wxuserExample.createCriteria().andUserIdEqualTo(userId);
            List<Wxuser> wxusers = wxuserMapper.selectByExample(wxuserExample);
            Wxuser wxuser = wxusers.get(0);
            map.put("Storephone",wxuser.getUserPhone());
        }else {
            map.put("Storephone","*******");
        }
        return ReturnResult.dataSuccess(map);
    }

    @Override
    public ReturnResult accessOrderBtn(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        String storeId = request.getParameter("storeId");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        if(storeToAssignment==null) return new ReturnResult("-1","订单不存在");
        if(!(storeId.equals(storeToAssignment.getStoreId()))) return new ReturnResult("-1","订单与小店不匹配");
        if(0==storeToAssignment.getStatus()){
            storeToAssignment.setStatus(1);
            storeToAssignment.setReceivingTime(new Date());
            int i = storeToAssignmentMapper.updateByPrimaryKey(storeToAssignment);
            if(i>0) return ReturnResult.success();
            else return ReturnResult.error();
        }
        return new ReturnResult("-1","当前状态无法接单");
    }

    @Override
    public ReturnResult accessArriveBtn(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        String storeId = request.getParameter("storeId");
        String latitude = request.getParameter("latitude");
        String longitude = request.getParameter("longitude");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        if(storeToAssignment==null) return new ReturnResult("-1","订单不存在");
        if(!(storeId.equals(storeToAssignment.getStoreId()))) return new ReturnResult("-1","订单与小店不匹配");
        String shootingAddress = storeToAssignment.getShootingAddress();
        String[] split = shootingAddress.split(",");
        String G1=split[2];
        String G2=split[3];
        double distance = DistanceUtil.getDistance(latitude, longitude, G1, G2);
        if(distance>500) return new ReturnResult("-1","距离未小于500不允许确认");
        if(1==storeToAssignment.getStatus()){
            storeToAssignment.setStatus(3);
            int i = storeToAssignmentMapper.updateByPrimaryKey(storeToAssignment);
            if(i>0) return ReturnResult.success();
            else return ReturnResult.error();
        }
        return new ReturnResult("-1","当前状态无法确认");
    }

    @Override
    public ReturnResult accessArriveBtnUser(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        String userId = request.getParameter("userId");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        if(storeToAssignment==null) return new ReturnResult("-1","订单不存在");
        if(!(userId.equals(storeToAssignment.getUserId()))) return new ReturnResult("-1","订单与用户不匹配");
        if(3==storeToAssignment.getStatus()){
            storeToAssignment.setStatus(4);
            int i = storeToAssignmentMapper.updateByPrimaryKey(storeToAssignment);
            if(i>0) return ReturnResult.success();
            else return ReturnResult.error();
        }
        return new ReturnResult("-1","当前状态无法确认");
    }

    @Override
    public ReturnResult accessSuccessBtnUser(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        String userId = request.getParameter("userId");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        if(storeToAssignment==null) return new ReturnResult("-1","订单不存在");
        if(!(userId.equals(storeToAssignment.getUserId()))) return new ReturnResult("-1","订单与用户不匹配");
        if(4==storeToAssignment.getStatus()){
            storeToAssignment.setStatus(5);
            int i = storeToAssignmentMapper.updateByPrimaryKey(storeToAssignment);
            if(i>0) return ReturnResult.success();
            else return ReturnResult.error();
        }
        return new ReturnResult("-1","当前状态无法确认");
    }

    @Override
    public ReturnResult cancelOrderBtn(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        String storeId = request.getParameter("storeId");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        if(storeToAssignment==null) return new ReturnResult("-1","订单不存在");
        if(!(storeId.equals(storeToAssignment.getStoreId()))) return new ReturnResult("-1","订单与小店不匹配");
        if(0==storeToAssignment.getStatus()){
            storeToAssignment.setStatus(6);
            storeToAssignment.setStoreId(null);
            int i = storeToAssignmentMapper.updateByPrimaryKey(storeToAssignment);
            if(i>0) return ReturnResult.success();
            else return ReturnResult.error();
        }
        return new ReturnResult("-1","当前状态无法取消");
    }

    @Override
    public ReturnResult cancelButWantOrderBtn(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        String storeId = request.getParameter("storeId");
        if(StringUtils.isEmpty(storeId)) return new ReturnResult("-1","小店不存在");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        if(storeToAssignment==null) return new ReturnResult("-1","订单不存在");
        Store store = storeMapper.selectByPrimaryKey(storeId);
        if(store.getUserId().equals(storeToAssignment.getUserId()))
            return new ReturnResult("-1","不允许刷单");
        if(6==storeToAssignment.getStatus()){
            storeToAssignment.setStoreId(storeId);
            storeToAssignment.setStatus(1);
            int i = storeToAssignmentMapper.updateByPrimaryKey(storeToAssignment);
            if(i>0) return ReturnResult.success();
            else return ReturnResult.error();
        }
        return new ReturnResult("-1","当前状态无法取消");
    }

    @Override
    @Transactional
    public ReturnResult CommentMyOrderToStore(StoreCommentWithBLOBs storeComment) {


        String orderId = storeComment.getOrderId();
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(orderId);
        if(storeToAssignment==null) return new ReturnResult("-1","订单不存在");
        Integer status = storeToAssignment.getStatus();
        if(status!=5) return new ReturnResult("-1","当前状态不允许评价");
        storeComment.setStoreId(storeToAssignment.getStoreId());
        storeComment.setCommentUid(storeToAssignment.getUserId());
        storeComment.setId(RandomUtil.randomNumbers(18));
        storeComment.setScore04(null);
        storeComment.setCreateTime(new Date());
        int i = storeCommentMapper.insertSelective(storeComment);
        if(i>0){
            StoreUserFollowExample storeUserFollowExample=new StoreUserFollowExample();
            storeUserFollowExample.createCriteria().andUserIdEqualTo(storeToAssignment.getUserId()).andStoreIdEqualTo(storeToAssignment.getStoreId());
            List<StoreUserFollow> storeUserFollows = storeUserFollowMapper.selectByExample(storeUserFollowExample);
            if(storeUserFollows.size()>0){
                storeToAssignment.setStatus(8);
            }else {
                storeToAssignment.setStatus(7);
            }
            int i1 = storeToAssignmentMapper.updateByPrimaryKeySelective(storeToAssignment);
            if(i1>0){
                StoreCommentExample storeCommentExample=new StoreCommentExample();
                storeCommentExample.createCriteria().andStoreIdEqualTo(storeComment.getStoreId());
                List<StoreComment> storeComments = storeCommentMapper.selectByExample(storeCommentExample);
                double server=0.0;//服务
                double economy=0.0;//质量
                double attitude=0.0;//态度
                for (StoreComment e:storeComments) {
                    economy += e.getScore01();
                    attitude += e.getScore02();
                    server += e.getScore03();
                }
                double all=(economy+attitude+server)/storeComments.size();
                Store store=new Store();
                store.setId(storeComment.getStoreId());
                store.setStar((int) all);
                int i2 = storeMapper.updateByPrimaryKeySelective(store);
                if (i2>0)
                return ReturnResult.success();
                else
                    return  ReturnResult.errortRollback("评论失败");
            }else
                return  ReturnResult.errortRollback("评论失败");
        }else {
            return ReturnResult.errortRollback("评论失败");
        }
    }

    @Override
    public ReturnResult selectComment(HttpServletRequest request) {
        String assignmentId = request.getParameter("assignmentId");
        String storeId = request.getParameter("storeid");
        StoreToAssignment storeToAssignment = storeToAssignmentMapper.selectByPrimaryKey(assignmentId);
        StoreCommentExample storeCommentExample=new StoreCommentExample();
        storeCommentExample.createCriteria().andOrderIdEqualTo(assignmentId);
        List<StoreCommentWithBLOBs> storeCommentWithBLOBs = storeCommentMapper.selectByExampleWithBLOBs(storeCommentExample);

        if(storeCommentWithBLOBs.size()>0){
            StoreCommentWithBLOBs storeCommentWithBLOBs1 = storeCommentWithBLOBs.get(0);
            Map<String, Object> map = BeanUtil.beanToMap(storeCommentWithBLOBs1);
            map.put("status",storeToAssignment.getStatus());
            return ReturnResult.dataSuccess(map);
        }else {
            return ReturnResult.dataSuccess(null);
        }
    }
}
